<?php
defined('IN_XLP') or die('Access Denied');
/*
 * 微信统一支付模型
 */
class alipayModel extends Model {

    public function __construct() {
        parent::__construct();
        T('alipay/alipay.app');
    }

    /*
     * 发起APP支付
     */
    public function callAppPay($arr=array(), $notify="") {
        try {
            $ali = new alipayApp();
            if($notify) {
                $ali->setNotifyURL($notify);
            }
            $param = $ali->getAppParam($arr);

            return $param;
        } catch (Exception $e) {
            $this->errorLog($e);
        }
    }

    /*
     * 验证支付宝通知
     */
    public function checkNotify() {
        try {
            $ali  = new alipayApp();
            $data = $ali->checkNotify();
            $this->notifyLog($data, "APP");

            return $data;
        } catch (Exception $e) {
            $this->errorLog($e);
        }
    }


    private function errorLog($exception=null) {
        if($exception) {
            $msg   = $exception->getMessage();
            $debug = $exception->getTraceAsString();
            saveLog('alipay/error', $msg.' ==> '.$debug);
            exit('fail');
        }
    }


    /*
     * 记录通知信息
     */
    private function notifyLog($data, $type="") {
        if($type) { //支付终端
            $type = '-'.$type;
        }
        M('unipay_log')->insert(array(
            'pay_type'       => 'Alipay'.$type,
            'out_trade_no'   => $data['out_trade_no'],
            'transaction_id' => $data['trade_no'],
            'total_fee'      => $data['total_fee']*100, //单位为分
            'time_end'       => isset($data['gmt_payment']) ? date('YmdHis', strtotime($data['gmt_payment'])) : '',
            'data_all'       => json_encode($data),
            'create_time'    => TIME,
        ));
    }

}